package com.ds.seqlist;

public class PractiseSingleLinkedList {
    private Node head = null;

    private int size =0 ;

    public void add(int index, int val){
        // TODO 判空
        if (index<0 || index>size){
            System.out.println("index有误！");
            return;
        }
        if (index==0){
            //TODO 头插
            addFirst(val);
        }
        Node newnode=new Node(val);
        Node pre = head;
        for (int i = 0; i < index-1; i++) {
            pre = pre.next;
        }
        newnode.next=pre.next;
        pre.next=newnode;
        size++;
    }

    public void addFirst(int val) {
        Node newNode = new Node();
        // 保存值
        newNode.val = val;
        if(head != null) {
            newNode.next = head;
        }
        // 无论是否为空，新节点都是插入后的链表头结点
        head = newNode;
        size ++;
    }


    public void addLast(int val){
        add(size,val);
    }

    public boolean contains(int val){
        Node temp = head;
        for (int i = 0; i < size; i++) {
            if(temp.val==val){
                return true;
            }
            temp = temp.next;
        }
        return false;
    }

    /**
     * toString方法重写
     * @return
     */
    @Override
    public String toString() {
        String string = "";
        Node temp = head;
        for (int i = 0; i < size-1; i++) {
            string += temp.val+"->";
            temp=temp.next;
        }
        string += "NULL";
        return string;
//        String ret = "";
//        for (Node x = head;x != null;x = x.next) {
//            ret += x.val;
//            ret += "->";
//        }
//        ret += "NULL";
//        return ret;
    }

    public void removeindex(int index){
        if(index<0||index>size-1){
            System.out.println("illegal");
            return;
        }
        if (index == 0){
            Node temp = head;
            head = head.next;
            temp.next=null;
            size--;
        }
        Node pre = head;
        for (int i = 0; i < index-1; i++) {
            pre = pre.next;
        }
        pre.next = pre.next.next;
    }

}

